#include "dataline.h"
#include "ui_dataline.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDateTime>
#include <QDebug>

DataLine* DataLine::m_instance = nullptr;  // 初始化静态实例

DataLine* DataLine::instance(QWidget *parent)
{
    if (m_instance == nullptr) {
        m_instance = new DataLine(parent);  // 如果没有实例，就创建一个
    }
    return m_instance;
}

DataLine::DataLine(QWidget *parent)
    : QWidget(parent),
      ui(new Ui::DataLine),
      dataSize(1000)  // 默认显示1000条数据
{
    ui->setupUi(this);

    // 初始化图表
    setupGraph();

    // 复选框默认勾选
    ui->currentCheckBox->setChecked(true);
    ui->voltageCheckBox->setChecked(true);
    ui->powerCheckBox->setChecked(true);

    // 设置信号与槽
    connect(ui->currentCheckBox, &QCheckBox::toggled, this, &DataLine::toggleGraphVisibility);
    connect(ui->voltageCheckBox, &QCheckBox::toggled, this, &DataLine::toggleGraphVisibility);
    connect(ui->powerCheckBox, &QCheckBox::toggled, this, &DataLine::toggleGraphVisibility);

    // 数据库连接
    connectToDatabase();

    // 更新数据
    updateData();
}

DataLine::~DataLine()
{
    delete ui;
}

void DataLine::setupGraph()
{
    // 初始化图表数据
    x.resize(dataSize);
    current.resize(dataSize);
    voltage.resize(dataSize);
    power.resize(dataSize);

    // 添加电流曲线
    ui->widget->addGraph();
    ui->widget->graph(0)->setName("电流");
    ui->widget->graph(0)->setPen(QPen(Qt::blue));

    // 添加电压曲线
    ui->widget->addGraph();
    ui->widget->graph(1)->setName("电压");
    ui->widget->graph(1)->setPen(QPen(Qt::red));

    // 添加功率曲线
    ui->widget->addGraph();
    ui->widget->graph(2)->setName("功率");
    ui->widget->graph(2)->setPen(QPen(Qt::green));

    // 设置坐标轴
    ui->widget->yAxis->setLabel("值");

    // 设置图例
    ui->widget->legend->setVisible(true);

    // 启用缩放和拖动
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
}

void DataLine::connectToDatabase()
{
    // 这里使用假设的数据库连接代码。根据实际情况修改：
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");  // 使用SQLite数据库，适配其他数据库类型
    db.setDatabaseName("../chargingpile.db");  // 数据库文件路径

    if (!db.open()) {
        qDebug() << "数据库连接失败: " << db.lastError().text();
    } else {
        qDebug() << "数据库连接成功";
    }
}

void DataLine::updateData()
{
    // 从数据库获取数据
    fetchData();

    if (!x.isEmpty()) {
        // 更新曲线数据
        ui->widget->graph(0)->setData(x, current);
        ui->widget->graph(1)->setData(x, voltage);
        ui->widget->graph(2)->setData(x, power);

        // 设置自定义X轴标签间隔
        QVector<QString> xLabels;
        QVector<double> labelPositions;  // 标签对应的位置
        int labelInterval = std::max(1, x.size() / 10);  // 每10%点显示一个标签

        for (int i = 0; i < x.size(); i += labelInterval) {
            QDateTime timestamp = QDateTime::fromMSecsSinceEpoch(x[i] * 1000);  // 秒转毫秒
            xLabels.append(timestamp.toString("hh:mm:ss"));  // 可改为"yyyy-MM-dd hh:mm:ss"根据需要
            labelPositions.append(x[i]);
        }

        // 使用文本标签更新X轴
        QSharedPointer<QCPAxisTickerText> xTicker(new QCPAxisTickerText);
        for (int i = 0; i < labelPositions.size(); ++i) {
            xTicker->addTick(labelPositions[i], xLabels[i]);
        }
        ui->widget->xAxis->setTicker(xTicker);

        // 调整坐标轴范围
        ui->widget->xAxis->setRange(x.first(), x.last());

        // 调整Y轴范围
        double minY = std::min({*std::min_element(current.begin(), current.end()),
                                *std::min_element(voltage.begin(), voltage.end()),
                                *std::min_element(power.begin(), power.end())});
        double maxY = std::max({*std::max_element(current.begin(), current.end()),
                                *std::max_element(voltage.begin(), voltage.end()),
                                *std::max_element(power.begin(), power.end())});
        ui->widget->yAxis->setRange(minY * 0.9, maxY * 1.1);

        // 刷新图表
        ui->widget->replot();
    }
}


void DataLine::fetchData()
{
    QSqlQuery query;
    query.prepare(R"(
        SELECT `当前时间`, `电流`, `电压`, `功率`
        FROM chargingpiles
        ORDER BY `当前时间` DESC
        LIMIT 1000
    )");

    if (query.exec()) {
        x.clear();
        current.clear();
        voltage.clear();
        power.clear();

        while (query.next()) {
            QString timestampStr = query.value(0).toString();
            QDateTime timestamp = QDateTime::fromString(timestampStr, "yyyy-MM-dd hh:mm:ss");
            if (timestamp.isValid()) {
                x.prepend(timestamp.toMSecsSinceEpoch() / 1000.0); // 转换为秒
                current.prepend(query.value(1).toDouble());
                voltage.prepend(query.value(2).toDouble());
                power.prepend(query.value(3).toDouble());
            } else {
                qDebug() << "时间解析失败:" << timestampStr;
            }
        }
    } else {
        qDebug() << "数据库查询失败:" << query.lastError().text();
    }
}

void DataLine::toggleGraphVisibility()
{
    QCheckBox *senderCheckBox = qobject_cast<QCheckBox *>(sender());
    if (!senderCheckBox) return;

    if (senderCheckBox == ui->currentCheckBox) {
        ui->widget->graph(0)->setVisible(senderCheckBox->isChecked());
    } else if (senderCheckBox == ui->voltageCheckBox) {
        ui->widget->graph(1)->setVisible(senderCheckBox->isChecked());
    } else if (senderCheckBox == ui->powerCheckBox) {
        ui->widget->graph(2)->setVisible(senderCheckBox->isChecked());
    }

    // 确保更新图表
    ui->widget->replot();
}


void DataLine::on_pushButton_pressed()
{
    qDebug() << "开始更新图像";

    // 更新数据
    updateData();

    // 显示控件
    ui->widget->setVisible(true);

    // 重新绘制图表
    ui->widget->replot();
}
